package cn.lijiguo.concurrency.part1.threadobjectmethods;

/**
 * WaitNotifyReleaseOwnMonitor
 * 证明 wait 只释放当前的那把锁
 * @author lijiguo
 * @date 2020/1/6 16:16
 */
public class WaitNotifyReleaseOwnMonitor {

    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (resourceA) {
                System.out.println(Thread.currentThread().getName() + " got resourceA lock.");

                synchronized (resourceB) {
                    System.out.println(Thread.currentThread().getName() + " got resourceB lock.");

                    try {
                        System.out.println(Thread.currentThread().getName() + " releases resourceA lock.");
                        resourceA.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (resourceA) {
                System.out.println(Thread.currentThread().getName() + " got resourceA lock.");

                System.out.println(Thread.currentThread().getName() + " tries to resourceB lock.");
                synchronized (resourceB) {
                    System.out.println(Thread.currentThread().getName() + " got resourceB lock.");
                }
            }
        }, "t2");

        t1.start();
        t2.start();
    }

}
